//
//  MarketIndexDetailTVC.m
//  RedManStock
//
//  Created by lanou3g on 15/7/28.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "MarketIndexDetailTVC.h"
#import "MaketIndexDetailTableViewCell.h"
#import "MyHandle.h"
#import "MarketIndex.h"
#import "StockHomeViewController.h"
#import "HeadControlView.h"
#import "UpList.h"
#import "DownList.h"
#import "TurnoverList.h"
#import "MarketDetailHeadView.h"
#import "MarketDetail.h"
#import "StockSimpleLineViewController.h"
#import "MBProgressHUD.h"
@interface MarketIndexDetailTVC ()

@property(nonatomic,retain)NSMutableArray *marketArray;
@property(nonatomic,retain)HeadControlView *headControlView;

@property(nonatomic,retain)NSMutableArray *upListArray;
@property(nonatomic,retain)NSMutableArray *downListArray;
@property(nonatomic,retain)NSMutableArray *turnoverArray;

@property (nonatomic,retain) StockSimpleLineViewController *stockSimpleLineVC;

@end

@implementation MarketIndexDetailTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.num = 0;
    self.upListArray = [NSMutableArray array];
    self.downListArray = [NSMutableArray array ];
    self.turnoverArray = [NSMutableArray array ];
    self.update = YES;
    [self.tableView registerNib:[UINib nibWithNibName:@"MaketIndexDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"marketIndex"];
    
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"MarketDetailHeadView" owner:self options:nil];
    self.marketHeadView=[nibView objectAtIndex:0];
    
    
    //    给headView上的属性赋值
    self.marketHeadView.marketDeatil = self.marketDetail;
    [self.tableView reloadData];
    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 420)];
    self.marketHeadView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 200);
    [self.tableView.tableHeaderView addSubview:self.marketHeadView];
    
    //设置导航栏标题
    self.navigationItem.titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
    UILabel *label1=[UILabel labelWithFrame:CGRectMake(0, 0, 150, 20) text:[NSString stringWithFormat:@"%@(%@)",self.idName,self.ID]];
    label1.font=[UIFont systemFontOfSize:14];
    label1.textAlignment=NSTextAlignmentCenter;
    UILabel *label2=[UILabel labelWithFrame:CGRectMake(0, 20, 150, 10) text:self.marketDetail.statusTimeSB];
    label2.font=[UIFont systemFontOfSize:11];
    label2.textAlignment=NSTextAlignmentCenter;
    label1.textColor=[UIColor whiteColor];
    label2.textColor=[UIColor whiteColor];
    [self.navigationItem.titleView addSubview:label1];
    [self.navigationItem.titleView addSubview:label2];
    
    
    //加入小K线图构成的子控制器，并把其根视图加在headView上
    self.stockSimpleLineVC=[[StockSimpleLineViewController alloc]init];
    self.stockSimpleLineVC.code=self.ID;
    self.stockSimpleLineVC.view.frame=CGRectMake(0, 200, self.view.bounds.size.width, 200);
    [self addChildViewController:self.stockSimpleLineVC];
    [self.view addSubview:self.stockSimpleLineVC.view];
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(void)viewWillAppear:(BOOL)animated{
    
    if (self.update) {
        [self loadNewData];
    }
    self.update = NO;
}

-(void)loadNewData{
    //    出现大菊花
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

//-------------------------上方headView部分-------------------------
    NSString *urlStr = @"http://api.gongniucaijing.com/quotation/info";
    [[MyHandle new] requestDataWithURLStr:urlStr parameterBlock:^NSDictionary *{
        
        NSDictionary *dic = @{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                              @"id":self.ID};
        return dic;
    } successBlock:^(NSDictionary *responseDic) {

        NSDictionary *dic = responseDic;
        NSDictionary*dataDic = [dic objectForKey:@"data"];
        MarketDetail *marketDetail = [[MarketDetail alloc]init];
        [marketDetail setValuesForKeysWithDictionary:dataDic];
        self.marketHeadView.marketDeatil = marketDetail;
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        
    } errorBlock:^(NSError *error) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        [self.tableView.header endRefreshing];

        
    }];
    
    
    
    
    
    
    
//----------------------下方榜单部分--------------------------------
    if (self.num == 0) {
        NSString *url = @"http://api.gongniucaijing.com/quotation/ranking";
        [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
            
            NSDictionary *dic  = @{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                                   @"id":self.ID,
                                   @"command":@"1",
                                   @"offset":[NSString stringWithFormat:@"%lu",(unsigned long)self.marketArray.count],
                                   @"number":@"50",
                                   @"type":@"market",
                                   @"order":@"up"
                                   };
            return dic;
        } successBlock:^(NSDictionary *responseDic) {
            [self dataSourceWithJasonDic:responseDic];
            [self.tableView.header endRefreshing];
        } errorBlock:^(NSError *error) {
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            
            [alertView show];
            [self.tableView.header endRefreshing];
            

            
        }];
    }else if (self.num == 1){
        
        NSString *url = @"http://api.gongniucaijing.com/quotation/ranking";
        [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
            
            NSDictionary *dic  = @{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                                   @"id":self.ID,
                                   @"command":@"1",
                                   @"offset":[NSString stringWithFormat:@"%lu",(unsigned long)self.marketArray.count],
                                   @"number":@"50",
                                   @"type":@"market",
                                   @"order":@"down"
                                   };
            return dic;
        } successBlock:^(NSDictionary *responseDic) {
            [self dataSourceWithJasonDic:responseDic];
            [self.tableView.header endRefreshing];
        } errorBlock:^(NSError *error) {
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            
            [alertView show];
            [self.tableView.header endRefreshing];

            
        }];
        
    }else{
        
        NSString *url = @"http://api.gongniucaijing.com/quotation/ranking";
        [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
            
            NSDictionary *dic  = @{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                                   @"id":self.ID,
                                   @"command":@"1",
                                   @"offset":[NSString stringWithFormat:@"%lu",(unsigned long)self.marketArray.count],
                                   @"number":@"50",
                                   @"type":@"turnover"
                                   
                                   };
            return dic;
        } successBlock:^(NSDictionary *responseDic) {
            [self dataSourceWithJasonDic:responseDic];
            [self.tableView.header endRefreshing];
        } errorBlock:^(NSError *error) {
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            
            [alertView show];
            [self.tableView.header endRefreshing];

            
        }];
    }
    

    
    
}






#pragma mark- 共用方法：数据源赋值，reloadData -
- (void)dataSourceWithJasonDic:(NSDictionary *)dic{

   
    if (self.num == 0) {
        
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        NSArray *listsArray = [dataDic objectForKey:@"lists"];
        for (NSDictionary *dic in listsArray) {
            
            UpList *upList = [[UpList alloc]init];
            [upList setValuesForKeysWithDictionary:dic];
            [self.upListArray addObject:upList];
            
        }
        //        结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.tableView reloadData];
        
    }else if (self.num == 1){
        
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        NSArray *listsArray = [dataDic objectForKey:@"lists"];
        for (NSDictionary *dic in listsArray) {
            
            DownList *downList = [[DownList alloc]init];
            [downList setValuesForKeysWithDictionary:dic];
            [self.downListArray addObject:downList];
            
        }
        //        结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.tableView reloadData];
        
    }else{
        
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        NSArray *listsArray = [dataDic objectForKey:@"lists"];
        for (NSDictionary *dic in listsArray) {
            
            TurnoverList *turnover = [[TurnoverList alloc]init];
            [turnover setValuesForKeysWithDictionary:dic];
            [self.turnoverArray addObject:turnover];
            
        }
        //        结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.tableView reloadData];
        
    }
    
    
    }







#pragma mark - 区头加标题 -
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    NSString *title = @"名称代码     最新价    涨跌幅    推荐数";
    return  title;
}


#pragma mark- 协议方法：分行 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.num == 0) {
        
        return self.upListArray.count;
    }else if (self.num == 1){
        return self.downListArray.count;
    }else{
        
        return self.turnoverArray.count;
    }
    
}

#pragma mark- 分区 -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


#pragma mark- 协议方法cell复用 -
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.num == 0) {
            MaketIndexDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"marketIndex" forIndexPath:indexPath];
        UpList *upList = [self.upListArray objectAtIndex:indexPath.row];
        cell.nowPriceLabel.textColor = MyRedColor;
        cell.updownRateLabel.textColor = MyRedColor;
        
//        CGFloat W = [UIScreen mainScreen].bounds.size.width;
//        CGFloat a = (W-300)/5;
//        
//        cell.nameLabel.frame = CGRectMake(a, cell.nameLabel.frame.origin.y, cell.nameLabel.frame.size.width, cell.nameLabel.frame.size.height);
//        cell.codeLabel.frame = CGRectMake(a, cell.codeLabel.frame.origin.y, cell.codeLabel.frame.size.width, cell.codeLabel.frame.size.height);
//        cell.nowPriceLabel.frame = CGRectMake(2*a+75, cell.nowPriceLabel.frame.origin.y, cell.nowPriceLabel.frame.size.width, cell.nowPriceLabel.frame.size.height);
//        cell.updownRateLabel.frame = CGRectMake(3*a+150, cell.updownRateLabel.frame.origin.y, cell.updownRateLabel.frame.size.width, cell.updownRateLabel.frame.size.height);
//        cell.recommendLabel.frame = CGRectMake(4*a+225, cell.recommendLabel.frame.origin.y, cell.recommendLabel.frame.size.width, cell.recommendLabel.frame.size.height);
        
        
        cell.upList = upList;
        return cell;
        
    }else if (self.num == 1){
            MaketIndexDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"marketIndex" forIndexPath:indexPath];
        DownList *downList = [self.downListArray objectAtIndex:indexPath.row];
        cell.nowPriceLabel.textColor = MyGreenColor;
        cell.updownRateLabel.textColor = MyGreenColor;
        cell.downList = downList;
        return cell;
    }else{
            MaketIndexDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"marketIndex" forIndexPath:indexPath];
        TurnoverList *turn = [self.turnoverArray objectAtIndex:indexPath.row];
        cell.nowPriceLabel.textColor = MyRedColor;
        cell.updownRateLabel.textColor = [UIColor blackColor];
        cell.turn = turn;
        return cell;
    }

   
}

#warning 这得约束有问题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    self.headControlView = nil;
    if (self.headControlView == nil) {
        
        self.headControlView = [[HeadControlView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 35) titleArray:@[@"涨幅榜",@"跌幅榜",@"换手率榜"]];
        
        CGFloat W = self.view.frame.size.width;
        CGFloat a = (W-240)/5;
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(a-10, 43, 60, 20)];
        label1.textAlignment = NSTextAlignmentCenter;
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(2*a+60, 43, 50, 20)];
        label2.textAlignment = NSTextAlignmentCenter;
        
        UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(3*a+120, 43, 50, 20)];
        label3.textAlignment = NSTextAlignmentCenter;
        
         UILabel *label4 = [[UILabel alloc]initWithFrame:CGRectMake(4*a+180+10, 43, 50, 20)];
        label4.textAlignment = NSTextAlignmentCenter;
        
        label1.text = @"股票名称";
        label1.font = [UIFont systemFontOfSize:13];
        label1.textColor = [UIColor whiteColor];
        
        label2.text = @"最新价";
        label2.font = [UIFont systemFontOfSize:13];
        label2.textColor = [UIColor whiteColor];
        
        label3.text = @"幅度";
        label3.font = [UIFont systemFontOfSize:13];
        label3.textColor = [UIColor whiteColor];
        
        label4.text = @"推荐数";
        label4.font = [UIFont systemFontOfSize:13];
        label4.textColor = [UIColor whiteColor];
        
        
        [self.headControlView addSubview:label1];
        [self.headControlView addSubview:label2];
        [self.headControlView addSubview:label3];
        [self.headControlView addSubview:label4];
        
        for (int i=0; i<_headControlView.buttonArray.count; i++) {
            UIButton *button=_headControlView.buttonArray[i];
            [button addTarget:self action:@selector(buttonClickToChangeWhich:) forControlEvents:UIControlEventTouchUpInside];
            
        }
    }
    
    if (self.num == 0) {
        
        self.headControlView.nowLocation = 0;
    }else if (self.num == 1){
        
        self.headControlView.nowLocation = 1;
    }else{
        
        self.headControlView.nowLocation = 2;
    }
    
    return self.headControlView;
}

//区头的button点击事件
- (void)buttonClickToChangeWhich:(UIButton *)button{
    NSInteger index = button.tag -1000;
    
    if (index == 0) {
        self.num = 0;
        [self loadNewData];
    }else if (index == 1){
        self.num = 1;
        [self loadNewData];
    }else{
        self.num = 2;
        [self loadNewData];
    }
    
    [self.tableView reloadData];
    
}


#pragma mark- cell被选中方法 -
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.num == 0) {
        
        StockHomeViewController *stockHome = [[StockHomeViewController alloc]init];
        UpList *upList = self.upListArray[indexPath.row];
        stockHome.stockCode = upList.codeSB;
        stockHome.stockName = upList.name;
        [self.navigationController pushViewController:stockHome animated:YES];
        
    }else if (self.num == 1){
        StockHomeViewController *stockHome = [[StockHomeViewController alloc]init];
        DownList *downList = self.downListArray[indexPath.row];
        stockHome.stockCode = downList.codeSB;
        stockHome.stockName = downList.name;
        [self.navigationController pushViewController:stockHome animated:YES];
        
    }else{
        
        StockHomeViewController *stockHome = [[StockHomeViewController alloc]init];
        TurnoverList *turn = self.turnoverArray[indexPath.row];
        stockHome.stockCode = turn.codeSB;
        stockHome.stockName = turn.name;
        [self.navigationController pushViewController:stockHome animated:YES];
        
        
    }
    
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return 62;
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
